package com.servlet.action;

import java.io.IOException;
import java.sql.*;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.info.UserInfo;

import com.servlet.UserListener;
import com.utils.DBmanager;
/*
 * Action接口,所有动作都必须实现改接口
 * perform函数: 执行请求, 无默认方法
 * write函数: 将字符串写进响应流, 具有默认实现
 */
public interface Action {
    public String perform(HttpServletRequest request, HttpServletResponse response) throws IOException;
    default public void write(HttpServletResponse response, String text) throws IOException {
    	if(text != "")
    		response.getWriter().append(text);		
    }
}
/*
 * 响应注册请求,若成功则将数据写入数据库
 */
class RegistAction implements Action{
	public String perform(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		//获取用户注册信息
		String username = (String)request.getParameter("username");
		String pwd = (String)request.getParameter("pwd");
		
		//判断用户注册名是否与数据库已有项重复
		if(!Registed(username)) {
			if(register(username,pwd)) {
				return "/"+"index.jsp";		//注册成功,返回登录页
			}else {
				String alert = "<script>alert('服务器错误,注册失败!');window.location.href = 'register.jsp';</script>";
				write(response,alert);
				return "";
			}
		}else {
			String alert = "<script>alert('该用户名已占用,注册失败!');window.location.href = 'register.jsp';</script>";
			write(response,alert);
			return "";
		}
	}
	//将用户信息写入写入数据库,成功返回true,否则返回false
	boolean register(String username,String pwd) {
		DBmanager db = DBmanager.getInstance();		
		try(Connection conn = db.getConnection();
			Statement sta = conn.createStatement()){
			int changedline = 0;			
			changedline = sta.executeUpdate("INSERT INTO wechat_users VALUE('"+username+"','"+pwd+"')");							
			if(changedline != 0) {//若查找到该昵称,则已注册				
				return true;								
			}
		} catch (SQLException e) {		
			e.printStackTrace();
			return false; //出现异常,注册失败
		}
		return false;
	}
	//判断用户名是否已注册, 是则返回true
	boolean Registed(String username) {
		DBmanager db = DBmanager.getInstance();		
		try(Connection conn = db.getConnection();
			Statement sta = conn.createStatement()){
			ResultSet set = null;
			try {
			set = sta.executeQuery("SELECT * FROM wechat_users WHERE username='"+username+"'");		
			while(set.next()) {
				System.out.println("username:"+set.getString(1)+" pwd: "+set.getString(2));
				//若密码与用户名匹配,返回true
				if(set.getString(1).equals(username)) {
					return true;
				}
			}	
			}finally{				
					set.close();					
				}								
		} catch (SQLException e) {		
			e.printStackTrace();
			return true; //出现异常,取消注册
		}
		return false;
	}
}
/*
 * 登录动作, 成功则跳转到聊天页,失败返回登录页
 */
class LoginAction implements Action{
	
	public String perform(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		//创建回话,获取在线列表
		boolean newSession = request.getSession().isNew();
		HttpSession session = request.getSession();
		String username = (String)request.getParameter("username");
		String pwd = (String)request.getParameter("pwd");
		UserInfo users = UserInfo.getInstance();
		List online = users.getList();
		
		//检验密码
		if(!checkPwd(username,pwd)) {
			String alert = "<script>alert('用户名或密码错误!');window.location.href = 'index.jsp';</script>";
			write(response,alert);
			return "";
		}
		//判断该账号是否在线
		if(newSession && online.contains(username)){
			String alert = "<script>alert('该账号已上线!');window.location.href = 'index.jsp';</script>";
			write(response,alert);
			return "";
		}else{		//正常登录	
			if(!online.contains(username)) {
				UserListener ul = new UserListener();
				ul.setUser(username);				
				users.addUser(username);
				session.setAttribute("username", username);
				session.setAttribute("userlistener", ul);		//将用户加入在线状态监听		
			}			
			return "/"+"main.jsp";
		}			
	}
	
	
	//检验密码, 匹配则返回true
	public boolean checkPwd(String username, String pwd) {
		
		DBmanager db = DBmanager.getInstance();	
		if(db == null) {
			System.out.println("checkpwd: db为null!");
		}
		try(Connection conn = db.getConnection();
			Statement sta = conn.createStatement()){
			System.out.println("conn is OK!");
			ResultSet set = null;
			try {
				if(sta == null) {
					System.out.println("sta为null!");
				}
				set = sta.executeQuery("SELECT * FROM wechat_users WHERE username='"+username+"'");
				if(set == null) {
					System.out.println("set为null!");
				}
			while(set.next()) {
				System.out.println("username:"+set.getString(1)+" pwd: "+set.getString(2));
				//若密码与用户名匹配,返回true
				if(set.getString(2).equals(pwd)) {
					return true;
				}
			}	
			}finally{
				set.close();
			}
		} catch (SQLException e) {			
			e.printStackTrace();
			return false;
		}
		return false;
	}
}
/*
 * 暂时未使用的类,该功能在main.jsp中已实现
 * 会话超时(默认30分钟),返回登录页, 防止用户直接登入聊天页
 */
class SessionOvertimeAction implements Action{
	public String perform(HttpServletRequest request, HttpServletResponse response) {
		return "/"+"index.jsp";
	}
}
/*
 * 消息发送动作,用户成功发送消息时触发
 * 获取用户发送的消息,构造消息的html格式,添加到消息列表
 */
class SendMsgAction implements Action{
	
	public String perform(HttpServletRequest request, HttpServletResponse response) throws IOException {		
		String from = (String)request.getParameter("from");
		String face = (String)request.getParameter("face");
		String color = (String)request.getParameter("color");
		String to = (String)request.getParameter("to");
		String content = (String)request.getParameter("content");
		
		String msg = "<div width='100%' style='word-wrap:break-word; word-break:normal'>"
		+"<font color='red'>"+from+"</font>"
		+face
		+"对"+"<font color='blue'>"+to+"</font>"
		+"说:<font color='"+color+"'>"+content+"</font></div>";
		
		String oldMessage = (String)request.getServletContext().getAttribute("message");
		request.getServletContext().setAttribute("message", oldMessage+msg);
		System.out.println(oldMessage+msg);
		
		response.getWriter().append(oldMessage+msg);
		return "";
	}
}	
/*
 * 刷新消息栏,用户发送消息后触发或由计时器自动触发
 * 同步用户端消息,使用Ajax异步通讯
 */
class UpdateMsgAction implements Action{
	public String perform(HttpServletRequest request, HttpServletResponse response) {
		try {
			write(response,request.getServletContext().getAttribute("message").toString());
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		return "";
	}
}
/*
 * 刷新在线用户栏,用户登录后触发或由计时器自动触发
 * 同步用户端在线栏,使用Ajax异步通讯
 */
class UpdateOnlineUser implements Action{
	public String perform(HttpServletRequest request, HttpServletResponse response) {		
		return "/"+"onlineUserList.jsp";
	}
}
class LeaveAction implements Action{
	public String perform(HttpServletRequest request, HttpServletResponse response) {	
		request.getSession().invalidate();
		return "/"+"index.jsp";
	}
}











